package com.ruoyi.payOrder.order.service.impl;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.Coupon;
import com.ruoyi.common.core.constant.CouponSourceConstants;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.remoteService.CouponRemoteService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import com.ruoyi.payOrder.order.mapper.OrderMapper;
import com.ruoyi.payOrder.order.domain.Order;
import com.ruoyi.payOrder.order.service.IOrderService;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 订单Service业务层处理
 *
 * @author zx
 * @date 2025-09-14
 */
@Service
public class OrderServiceImpl implements IOrderService {
    @Resource
    private OrderMapper orderMapper;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private CouponRemoteService couponRemoteService;
    @Resource
    ElasticsearchRestTemplate restTemplate;
    // 最大重试次数（建议3-5次）
    private static final int MAX_RETRY_COUNT = 3;
    // 重试间隔（毫秒，建议1-3秒）
    private static final long RETRY_INTERVAL = 1000;
    // 存储每个消息的重试次数（key：消息ID，value：已重试次数）
    private final ConcurrentHashMap<String, Integer> retryCountMap = new ConcurrentHashMap<>();

    private final String exchangeName = "normal_fanout_exchange";
    private final String routeKey = "";

    /**
     * 初始化RabbitTemplate的ConfirmCallback
     */
    @PostConstruct
    public void initRabbitTemplate() {
        //消息确认回调，只设置一次
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            String messageId = "";
            if (correlationData != null) {
                messageId = correlationData.getId();
            }

            if (ack) {
                System.out.println("消息发送成功！！消息ID：" + messageId);
                return;
            }

            System.out.println("消息发送失败，消息ID：" + messageId);

            while (retryCountMap.getOrDefault(messageId, 0) < MAX_RETRY_COUNT) {
                try {
                    //模拟时间间隔
                    Thread.sleep(RETRY_INTERVAL);

                    Integer retryCount = retryCountMap.getOrDefault(messageId, 0);
                    retryCount++;
                    retryCountMap.put(messageId, retryCount);
                    // 注意：这里需要重新发送消息，但需要原始数据
                    System.out.println("重试发送消息，第" + retryCount + "次");
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException(e);
                }
            }
        });
    }

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public Order selectOrderById(Long id) {
        return orderMapper.selectOrderById(id);
    }

    /**
     * 查询订单列表
     *
     * @param order 订单
     * @return 订单
     */
    @Override
    public List<Order> selectOrderList(Order order) {
        return orderMapper.selectOrderByMultiTable(order);
    }

    /**
     * 全查订单列表（不分页，过滤逻辑删除）
     *
     * @param order 订单
     * @return 订单
     */
    @Override
    public List<Order> selectAllOrder(Order order)
    {
        return orderMapper.selectAllOrder(order);
    }

    /**
     * 新增订单
     *
     * @param order 订单
     * @return 结果
     */
    @Override
    public int insertOrder(Order order) throws JsonProcessingException {

        //判断优惠券
        //获取到平台优惠券的id
        Long platformCouponId = order.getPlatformCouponId();
        //获取到商家优惠券的id
        Long shopCouponId = order.getShopCouponId();


        if ((platformCouponId!=null && platformCouponId.equals(shopCouponId))) {
            throw new RuntimeException("优惠券选择错误，商家优惠券和平台优惠券重复");
        }

        System.out.println(couponRemoteService);


        if (platformCouponId!=null){
            R<Coupon> platform = couponRemoteService.getInfo(platformCouponId, SecurityConstants.INNER);
                System.out.println("优惠券数据：：" + platform);
            Coupon platformCoupon = platform.getData();
            Long platformSource = platformCoupon.getSource();
                if (platformSource != CouponSourceConstants.PLATFORM){
                    throw new  RuntimeException("优惠券未知异常");
                }

        }


        if (shopCouponId!=null){
            R<Coupon> shop = couponRemoteService.getInfo(shopCouponId,SecurityConstants.INNER);
            Coupon shopCoupon = shop.getData();
            Long shopSource = shopCoupon.getSource();
            if (shopSource != CouponSourceConstants.MERCHANT){
                throw new RuntimeException("优惠券未知异常");
            }
        }





        //将数据插入到数据库中，拿到id
        int rows = orderMapper.insertOrder(order);


        //发送消息的设置数据
        CorrelationData sendCorrelationData = new CorrelationData();
        sendCorrelationData.setId(System.currentTimeMillis()+"");

        //将消息发送到MQ中
        rabbitTemplate.convertAndSend(exchangeName,routeKey,order.getId(),sendCorrelationData);
        //返回结果

        return rows;
    }

    /**
     * 修改订单
     *
     * @param order 订单
     * @return 结果
     */
    @Override
    public int updateOrder(Order order) {
        return orderMapper.updateOrder(order);
    }

    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderByIds(Long[] ids) {
        return orderMapper.deleteOrderByIds(ids);
    }

    /**
     * 删除订单信息
     *
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteOrderById(Long id) {
        return orderMapper.deleteOrderById(id);
    }



    /**
     * 支付成功修改订单状态
     * @param id
     * @return
     */
    @Override
    public int payment(Long id) {
        return orderMapper.payment(id);
    }


    /**
     * 退款
     */
    @Override
    public int refund(Long id) {
        return orderMapper.refund(id);
    }


    /**
     * 核销完成之后，修改订单状态
     * @param id
     * @return
     */
    @Override
    public int verification(Long id) {
        return orderMapper.verification(id);
    }


    /**
     * 完成评价之后，修改订单状态
     * @param id
     * @return
     */
    @Override
    public int complete(Long id) {
        return orderMapper.complete(id);
    }

    @Override
    public int statistics(Long id) {
        /**
         * 服务详情编号id：主要用于做数据报表 【年终数据报表】，使用ES进行聚合查询
         * 维修：1928单
         * 保养：3261单
         * 保养套餐1：1200
         * 保养套餐2：500
         * 保养套餐3：1561
         * 洗车：1522单
         */
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        return 0;
    }

}
